package com.ruoyi.system.service.impl;

import com.itextpdf.text.pdf.PdfReader;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.EnterpriseInfoVO;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.schedule.ScheduledTaskService;
import com.ruoyi.system.schedule.TimingTask;
import com.ruoyi.system.service.IGwContractDetailService;
import com.ruoyi.system.service.IGwContractService;
import com.ruoyi.system.utils.AgentUtil;
import com.ruoyi.system.utils.FilePagesUtils;
import com.ruoyi.system.utils.PdfUtil;
import com.tencent.essbasic.api.*;
import com.tencent.essbasic.bytemplate.ByTemplate;
import com.tencentcloudapi.essbasic.v20210526.models.*;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.tencent.essbasic.common.CreateFlowUtils.convertImageFileToBase64;


/**
 * 合同管理Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-23
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class GwContractServiceImpl implements IGwContractService {

    @Resource
    private GwContractMapper gwContractMapper;
    @Resource
    private IGwContractDetailService gwContractDetailService;
    @Resource
    private GwCustomerInfoMapper gwCustomerInfoMapper;
    @Resource
    private GwStaffMapper gwStaffMapper;
    @Resource
    private GwInvestorInfoMapper gwInvestorInfoMapper;
    @Resource
    private GwEnterpriseInfoMapper gwEnterpriseInfoMapper;
    @Resource
    private AgentUtil agentUtil;
    @Resource
    ScheduledTaskService scheduledTaskService;

    /**
     * 查询合同管理
     *
     * @param id 合同管理主键
     * @return 合同管理
     */
    @Override
    public GwContract selectGwContractById(String id) {
        return gwContractMapper.selectGwContractById(Long.valueOf(id));
    }

    /**
     * 查询合同管理列表
     *
     * @param gwContract 合同管理
     * @return 合同管理
     */
    @Override
    public List<GwContract> selectGwContractList(GwContract gwContract) {
        //设置公司ID
        String companyId = ObjectUtils.isNotEmpty(SecurityUtils.getLoginUser().getEnterpriseId()) ? SecurityUtils.getLoginUser().getEnterpriseId() : "-1";
        gwContract.setCompanyId(companyId);
        //企业管理员看公司的
        if (!"1".equals(SecurityUtils.getLoginUser().getUser().getUserType())) {
            //其他人看自己创建的
            gwContract.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        }
        return gwContractMapper.selectGwContractList(gwContract);
    }

    @Override
    public List<GwContract> getGwContractByTypeAndUserId(String type, String userId, String status) {
        return gwContractMapper.getGwContractByTypeAndUserId(type, userId, status);
    }

    /**
     * 新增合同管理
     *
     * @param gwContract 合同管理
     * @return 结果
     */
    @Override
    public int insertGwContract(GwContract gwContract) {
        // 设置公司ID
        if (ObjectUtils.isEmpty(SecurityUtils.getLoginUser().getEnterpriseId())) {
            throw new GlobalException("未知的公司,请绑定公司再进行操作");
        }
        gwContract.setCompanyId(SecurityUtils.getLoginUser().getEnterpriseId());
        //gwContract.setId(IdUtils.fastSimpleUUID());

        String[] split = gwContract.getContractName().split("_");
        gwContract.setContractName(split[0]);

        gwContract.setIzHistory("是");
//        gwContract.setIzZt("");
        gwContract.setCreateTime(DateUtils.getNowDate());
        gwContract.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        gwContract.setUpdateTime(DateUtils.getNowDate());
        gwContract.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        //合同签署完成
        gwContract.setStatus("ALL");
        gwContract.setStatusName("合同签署完成");
        if (ObjectUtils.isEmpty(gwContract.getUserIds())) {
            throw new GlobalException("关联人员不能为空");
        }
        gwContractMapper.insertGwContract(gwContract);

        for (String id : gwContract.getUserIds().split(",")) {
            //添加关联人员
            GwContractDetail gwContractDetail = new GwContractDetail();
            gwContractDetail.setContractId(gwContract.getId() + "");
            gwContractDetail.setUserId(id);
            //判断那种类型
            if ("公司治理".equals(gwContract.getContractType())) {
                GwInvestorInfo gwInvestorInfo = gwInvestorInfoMapper.selectGwInvestorInfoById(id);
                gwContractDetail.setName(gwInvestorInfo.getInvestorName());
                gwContractDetail.setTel(gwInvestorInfo.getPhoneNumber());
            }
            if ("员工关系".equals(gwContract.getContractType())) {
                GwStaff gwStaff = gwStaffMapper.selectGwStaffById(id);
                gwContractDetail.setName(gwStaff.getStaffName());
                gwContractDetail.setTel(gwStaff.getTel());
            }
            if ("合同管理".equals(gwContract.getContractType())) {
                GwCustomerInfo gwCustomerInfo = gwCustomerInfoMapper.selectGwCustomerInfoById(id);
                gwContractDetail.setName(gwCustomerInfo.getCustomerName());
                gwContractDetail.setTel(gwCustomerInfo.getPhoneNumber());
            }
            //已签署
            gwContractDetail.setStatus("ACCEPT");
            gwContractDetail.setStatusName("已签署");
            gwContractDetailService.insertGwContractDetail(gwContractDetail);
        }

        return 1;
    }

    @Override
    public GwContract addSign(GwContract gwContract) {

        if (ObjectUtils.isEmpty(SecurityUtils.getLoginUser().getEnterpriseId())) {
            throw new GlobalException("未知的公司,请绑定公司再进行操作");
        }

        EnterpriseInfoVO myEnterpriseInfo = gwEnterpriseInfoMapper.getLoginEnterpriseInfo(SecurityUtils.getLoginUser().getEnterpriseId());
        if (ObjectUtils.isEmpty(myEnterpriseInfo)) {
            throw new GlobalException("未知的公司，操作失败!!!");
        }

        if (ObjectUtils.isEmpty(gwContract.getUserIds())) {
            throw new GlobalException("签署人员不能为空");
        }
        String[] strings = gwContract.getUserIds().split(",");

        // 判断企业的剩余合同份数，
        // 若余额不足，弹窗提示“剩余合同份数余额不足，是否立即充值？”
        // 用户点击取消返回先前界面；
        // 用户点击确认跳转到平台权益套餐的合同份数套餐界面；
        // 若余额充足则弹窗打开

        if (ObjectUtils.isEmpty(myEnterpriseInfo.getContractSurplusNum()) || myEnterpriseInfo.getContractSurplusNum() < 1) {
            throw new GlobalException("剩余合同份数余额不足，操作失败!!!");
        }

        // 发送短信时需扣除企业的短信条数，
        // 当短信条数余额不足时，弹窗提示“当前短信条数余额不足，是否立即充值？”
        // 用户点击取消时回到选择对象界面，
        // 点击确认时跳转到权益套餐的短信条数套餐界面

        if (ObjectUtils.isEmpty(myEnterpriseInfo.getSmsSurplusNum()) || myEnterpriseInfo.getSmsSurplusNum() < strings.length) {
            throw new GlobalException("当前短信条数余额不足，操作失败!!!");
        }

        Agent agent = agentUtil.setAgent();

        //设置公司ID
        gwContract.setCompanyId(SecurityUtils.getLoginUser().getEnterpriseId());
        gwContract.setIzHistory("否");
        gwContract.setCreateTime(DateUtils.getNowDate());
        gwContract.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        gwContract.setUpdateTime(DateUtils.getNowDate());
        gwContract.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());

        //合同创建
        gwContract.setStatus("INIT");
        gwContract.setStatusName("合同创建");

        List<GwContractDetail> gwContractDetails = new ArrayList<>();

        List<FlowApproverInfo> approvers = new ArrayList<>();
        List<CommonFlowApprover> commonFlowApprovers = new ArrayList<>();

        //获取当前登陆人公司信息
        GwEnterpriseInfo gwEnterpriseInfo = gwEnterpriseInfoMapper.selectGwEnterpriseInfoById(gwContract.getCompanyId());

        for (String id : strings) {

            //选择了自己公司
            if ("0".equals(id)) {
                // 公司签署信息
                FlowApproverInfo organizationApprover = new FlowApproverInfo();
                organizationApprover.setApproverType("ORGANIZATION");
                organizationApprover.setOrganizationName(gwEnterpriseInfo.getEnterpriseName());
                organizationApprover.setName(gwEnterpriseInfo.getContacts());
                organizationApprover.setMobile(gwEnterpriseInfo.getPhone());
                //两个openID
                organizationApprover.setOrganizationOpenId(agent.getProxyOrganizationOpenId());
                organizationApprover.setOpenId(agent.getProxyOperator().getOpenId());

                CommonFlowApprover commonOrganizationFlowApprover = new CommonFlowApprover();
                commonOrganizationFlowApprover.setNotChannelOrganization(false);
                commonOrganizationFlowApprover.setApproverType(0L);

                //通过文件发起合同
                if ("导入本地文件".equals(gwContract.getInitiationMethod())) {
                    List<Component> signComponents = new ArrayList<>();
                    Component component = new Component();
                    component.setComponentType("SIGN_SEAL");

                    component.setComponentHeight(100.0f);
                    component.setComponentWidth(100.0f);

                    //获取文档页数
                    long pageNum = getPageNum(gwContract.getContractUrl());
                    component.setComponentPage(pageNum);
                    component.setComponentPosX(400F);
                    component.setComponentPosY(400F);
                    component.setRelativeLocation("Right");

                    signComponents.add(component);
                    commonOrganizationFlowApprover.setSignComponents(signComponents.toArray(new Component[0]));
                }

                //两个openID
                commonOrganizationFlowApprover.setOrganizationOpenId(agent.getProxyOrganizationOpenId());
                commonOrganizationFlowApprover.setOpenId(agent.getProxyOperator().getOpenId());
                commonOrganizationFlowApprover.setOrganizationName(gwEnterpriseInfo.getEnterpriseName());

                //目前是企业公司的电话号联系人
                commonOrganizationFlowApprover.setApproverName(gwEnterpriseInfo.getContacts());
                commonOrganizationFlowApprover.setApproverMobile(gwEnterpriseInfo.getPhone());
                //todo 可修改为当前登录人
                //commonOrganizationFlowApprover.setApproverName(SecurityUtils.getLoginUser().getUser().getPhonenumber());
                //commonOrganizationFlowApprover.setApproverMobile(SecurityUtils.getLoginUser().getUser().getNickName());

                approvers.add(organizationApprover);
                commonFlowApprovers.add(commonOrganizationFlowApprover);

                //公司就子表不存了
//                GwContractDetail gwContractDetail = new GwContractDetail();
//                gwContractDetail.setUserId(id);
//                gwContractDetail.setName(gwEnterpriseInfo.getEnterpriseName());
//                gwContractDetail.setTel(gwEnterpriseInfo.getContacts());
//                gwContractDetail.setStatus("PENDING");
//                gwContractDetail.setStatusName("待签署");
//                gwContractDetails.add(gwContractDetail);

                continue;
            }

            String name = "";
            String tel = "";
            String contact = "";
            String type = "";
            //签署人员
            FlowApproverInfo approverInfo = new FlowApproverInfo();

            CommonFlowApprover commonFlowApprover = new CommonFlowApprover();

            if ("公司治理".equals(gwContract.getContractType())) {
                GwInvestorInfo gwInvestorInfo = gwInvestorInfoMapper.selectGwInvestorInfoById(id);
                name = gwInvestorInfo.getInvestorName();
                contact = gwInvestorInfo.getContact();
                tel = gwInvestorInfo.getPhoneNumber();
                type = gwInvestorInfo.getInvestorType();
            }
            if ("员工关系".equals(gwContract.getContractType())) {
                GwStaff gwStaff = gwStaffMapper.selectGwStaffById(id);
                contact = gwStaff.getStaffName();
                name = gwStaff.getStaffName();
                tel = gwStaff.getTel();
                type = "个人";
            }
            if ("合同管理".equals(gwContract.getContractType())) {
                GwCustomerInfo gwCustomerInfo = gwCustomerInfoMapper.selectGwCustomerInfoById(id);
                name = gwCustomerInfo.getCustomerName();
                tel = gwCustomerInfo.getPhoneNumber();
                contact = gwCustomerInfo.getContact();
                type = gwCustomerInfo.getCustomerType();
            }
            GwContractDetail gwContractDetail = new GwContractDetail();
            gwContractDetail.setUserId(id);
            gwContractDetail.setName(name);
            gwContractDetail.setTel(tel);
            gwContractDetail.setStatus("PENDING");
            gwContractDetail.setStatusName("待签署");
            gwContractDetails.add(gwContractDetail);

            if ("企业".equals(type)) {
                // 公司签署信息
                approverInfo.setApproverType("ORGANIZATION");
                approverInfo.setOrganizationName(name);
                // 渠道外企业，即 SaaS 企业， 即 ApproverType=ORGANIZATION且NotChannelOrganization=True
                approverInfo.setNotChannelOrganization(true);

                commonFlowApprover.setApproverType(0L);
                commonFlowApprover.setOrganizationName(name);
                commonFlowApprover.setNotChannelOrganization(true);
            } else {
                approverInfo.setApproverType("PERSON");
                commonFlowApprover.setApproverType(1L);
            }

            approverInfo.setName(contact);
            approverInfo.setMobile(tel);
            // approverInfo.setNotifyType("sms");

            commonFlowApprover.setApproverName(name);
            commonFlowApprover.setApproverMobile(tel);

            approvers.add(approverInfo);
            commonFlowApprovers.add(commonFlowApprover);
        }

        //发起签署流程
        if ("平台模板".equals(gwContract.getTemplateType()) || "公司模板".equals(gwContract.getTemplateType())) {

            if (ObjectUtils.isEmpty(gwContract.getContractUrl())) {
                throw new GlobalException("模板ID不能为空");
            }

            //获取签署人列表
            Recipient[] recipients = ByTemplate.GetRecipients(gwContract.getContractUrl(), agent);
            List<Recipient> collect1 = Arrays.stream(recipients).collect(Collectors.toList());

            if (commonFlowApprovers.size() != recipients.length) {
                throw new GlobalException("签署人员数量不一致,操作失败");
            }

            // 设置RecipientId
            for (int i1 = 0; i1 < commonFlowApprovers.size(); i1++) {
                CommonFlowApprover commonFlowApprover = commonFlowApprovers.get(i1);
                FlowApproverInfo flowApproverInfo = approvers.get(i1);
                Long approverType = commonFlowApprover.getApproverType();
                String approverType1 = flowApproverInfo.getApproverType();
                List<Recipient> collect;
                if (0L == approverType || "ORGANIZATION".equals(approverType1)) {
                    // 企业"ENTERPRISE"
                    collect = collect1.stream().filter(r -> "ENTERPRISE".equals(r.getRecipientType())).collect(Collectors.toList());
                } else if (1L == approverType || "PERSON".equals(approverType1)) {
                    // 自然人INDIVIDUAL
                    collect = collect1.stream().filter(r -> "INDIVIDUAL".equals(r.getRecipientType())).collect(Collectors.toList());
                } else {
                    //企业/企业员工自动签
                    collect = collect1.stream().filter(r -> "ENTERPRISE".equals(r.getRecipientType()) && !"INDIVIDUAL".equals(r.getRecipientType())).collect(Collectors.toList());
                }

                if (ObjectUtils.isNotEmpty(collect)) {
                    Recipient recipient = collect.get(0);
                    commonFlowApprover.setRecipientId(recipient.getRecipientId());
                    flowApproverInfo.setRecipientId(recipient.getRecipientId());
                    collect1.remove(recipient);
                }
            }

            if ("APP".equals(gwContract.getFrom())) {
                //通过模板创建流程
                Map<String, String[]> flowByTemplateDirectly = CreateFlowByTemplateDirectly.createFlowByTemplateDirectly(gwContract.getContractName(), gwContract.getContractUrl(), approvers.toArray(new FlowApproverInfo[0]), gwContract.getFormFields(), agent);
                gwContract.setContractId(flowByTemplateDirectly.get("FlowIds")[0]);
                gwContract.setSignLink(flowByTemplateDirectly.get("Urls")[0]);
            } else {
                gwContract.setStatus("PREPARE");
                gwContract.setStatusName("准备");
                // PC端通过模板创建预创建合同流程
                ChannelCreatePrepareFlowResponse ccf = ChannelCreatePrepareFlow.channelCreatePrepareFlow(gwContract.getContractName(), gwContract.getContractType(), gwContract.getContractUrl(), commonFlowApprovers.toArray(new CommonFlowApprover[0]), agent, 1L, false);
                gwContract.setContractId(ccf.getFlowId());
                gwContract.setPrepareFlowUrl(ccf.getPrepareFlowUrl());
                gwContract.setPreviewFlowUrl(ccf.getPreviewFlowUrl());
            }
        } else {
            String resourceId = null;
            String base64 = null;
            if (ObjectUtils.isNotEmpty(gwContract.getContractUrl())) {
                String replace = gwContract.getContractUrl().substring(15);
                base64 = convertImageFileToBase64(RuoYiConfig.getUploadPath() + replace);
            }

            if ("APP".equals(gwContract.getFrom())) {
                //old
                if (ObjectUtils.isEmpty(gwContract.getContractUrl())) {
                    throw new GlobalException("合同文件不能为空");
                }

                Map<String, String> flowByFileDirectly = CreateFlowByFileDirectly.createFlowByFileDirectly(gwContract.getContractName(), base64, approvers.toArray(new FlowApproverInfo[0]), agent);
                gwContract.setContractId(flowByFileDirectly.get("flowId"));
                gwContract.setSignLink(flowByFileDirectly.get("url"));
            } else {
                //new 2025.8.21
                if (ObjectUtils.isNotEmpty(gwContract.getContractUrl())) {
                    //上传文件
                    UploadFile[] uploadFiles = new UploadFile[]{new UploadFile()};
                    uploadFiles[0].setFileBody(base64);
                    UploadFilesResponse uploadRes = UploadFiles.uploadFiles(agent, uploadFiles);
                    resourceId = uploadRes.getFileIds()[0];
                }
                gwContract.setStatus("PREPARE");
                gwContract.setStatusName("准备");
                // PC端通过文件、公司模板发起预创建合同流程
                ChannelCreatePrepareFlowResponse ccf = ChannelCreatePrepareFlow.channelCreatePrepareFlow(gwContract.getContractName(), gwContract.getContractType(), resourceId, commonFlowApprovers.toArray(new CommonFlowApprover[0]), agent, 2L, ObjectUtils.isNotEmpty(resourceId));
                gwContract.setContractId(ccf.getFlowId());
                gwContract.setPrepareFlowUrl(ccf.getPrepareFlowUrl());
                gwContract.setPreviewFlowUrl(ccf.getPreviewFlowUrl());
            }
        }
        //保存合同信息
        gwContractMapper.insertGwContract(gwContract);
        if ("PREPARE".equals(gwContract.getStatus())) {
            //设置定时执行取消任务
            Instant instantPush = gwContract.getCreateTime().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            ZonedDateTime zonedDateTime = instantPush.atZone(zoneId);
            LocalDateTime pushTime = zonedDateTime.toLocalDateTime().plusMinutes(31);
            Instant instant = pushTime.atZone(ZoneId.systemDefault()).toInstant();
            List<TimingTask> startTasks = new ArrayList<>();
            TimingTask taskVo = new TimingTask();
            //执行任务时间
            Date date = Date.from(instant);
            taskVo.setStartDate(date);
            taskVo.setTempFlag(true);
            taskVo.setOrderId(gwContract.getId() + "");
            startTasks.add(taskVo);
            scheduledTaskService.startTask(startTasks);
        }

        //插入行表
        for (GwContractDetail gwContractDetail : gwContractDetails) {
            gwContractDetail.setContractId(gwContract.getId() + "");
            gwContractDetailService.insertGwContractDetail(gwContractDetail);
        }
        //增加合同数 && 短信数
        myEnterpriseInfo = gwEnterpriseInfoMapper.getLoginEnterpriseInfo(SecurityUtils.getLoginUser().getEnterpriseId());
        GwEnterpriseInfo enterpriseInfo = new GwEnterpriseInfo();
        enterpriseInfo.setId(myEnterpriseInfo.getId());
        enterpriseInfo.setSmsUseNum(myEnterpriseInfo.getSmsUseNum() + strings.length);
        enterpriseInfo.setContractUseNum(myEnterpriseInfo.getContractUseNum() + 1);
        gwEnterpriseInfoMapper.updateGwEnterpriseInfo(enterpriseInfo);
        return gwContract;
    }

    private long getPageNum(String contractUrl) {
        long num = 1L;
        if (ObjectUtils.isEmpty(contractUrl)) {
            return num;
        }
        try {
            String filePath = RuoYiConfig.getUploadPath() + contractUrl.substring(15);
            File file = new File(filePath);
            InputStream fis = Files.newInputStream(file.toPath());
            String ext = FilenameUtils.getExtension(contractUrl).toLowerCase();
            num = FilePagesUtils.filesPage(fis, ext);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException(e.getMessage());
        }
        return num;
    }

    @Override
    public AjaxResult revoke(GwContract gwContract) {
        if (ObjectUtils.isEmpty(gwContract.getCancelMessage())) {
            return AjaxResult.error("请输入撤销原因");
        }
        Agent agent = agentUtil.setAgent();
        GwContract query = gwContractMapper.selectGwContractById(gwContract.getId());
        ChannelCancelFlow.channelCancelFlow(agent, query.getContractId(), gwContract.getCancelMessage(), 1L);
        return AjaxResult.success();
    }

    @Override
    public Map<String, String> getDownUrl(GwContract gwContract) {
        Map<String, String> map = new HashMap<>();
        GwContract query = gwContractMapper.selectGwContractById(gwContract.getId());
        if (ObjectUtils.isNotEmpty(query)) {
            if ("是".equals(query.getIzHistory())) {
                // 本地地址
                map.put("url", query.getContractUrl());
                map.put("url2", query.getContractUrl());
            } else {
                //获取地址
                String s = DescribeFileUrls.describeFileUrls(gwContract.getContractId(), agentUtil.setAgent());

                String[] flowIds = new String[]{gwContract.getContractId()};
                String FileName = query.getContractName();
                DownloadFlowInfo downloadFlowInfo = new DownloadFlowInfo();
                downloadFlowInfo.setFileName(FileName);
                downloadFlowInfo.setFlowIdList(flowIds);
                GetDownloadFlowUrlResponse downloadFlowUrl = GetDownloadFlowUrl.getDownloadFlowUrl(new DownloadFlowInfo[]{downloadFlowInfo}, agentUtil.setAgent());
                map.put("url", downloadFlowUrl.getDownLoadUrl());
                map.put("url2", s);
            }
        } else {
            throw new GlobalException("未知的合同");
        }
        return map;
    }

    @Override
    public AjaxResult getSignUrl(GwContract gwContract) {
        GwContract query = gwContractMapper.selectGwContractById(gwContract.getId());
        if (ObjectUtils.isNotEmpty(query)) {
            try {
                String Endpoint = "APP";
                Agent agent = agentUtil.setAgent();
                String[] flowIds = new String[1];
                flowIds[0] = query.getContractId();
                CreateSignUrlsResponse signUrls = CreateSignUrls.createSignUrls(flowIds, agent, Endpoint);
                //不知道会不会变掉用接口
                Map<String, String> map = new HashMap<>();
                if (signUrls != null && ObjectUtils.isNotEmpty(signUrls.getSignUrlInfos())) {
                    SignUrlInfo[] signUrlInfos = signUrls.getSignUrlInfos();
                    map.put("url", signUrlInfos[0].getSignUrl());
                } else {
                    assert signUrls != null;
                    return AjaxResult.error(signUrls.getErrorMessages()[0]);
                }
                return AjaxResult.success(map);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error(e.getMessage());
            }
        } else {
            return AjaxResult.error("未知的合同");
        }
    }

    @Override
    public AjaxResult getTemplateParam(GwContract gwContract) {
        DescribeTemplatesResponse describeTemplatesResponse = DescribeTemplates.describeTemplates(agentUtil.setAgent(), gwContract.getContractUrl());
        return AjaxResult.success(describeTemplatesResponse);
    }

    @Override
    public GwContract selectGwContractByContractId(String contractId) {
        return gwContractMapper.selectGwContractByContractId(contractId);
    }

    @Override
    public List<GwContract> selectGwContractAllList(GwContract gwContract) {
        return gwContractMapper.selectGwContractList(gwContract);
    }

    @Override
    public AjaxResult getPdfPics(GwContract gwContract) {
        if (ObjectUtils.isEmpty(gwContract.getContractUrl())) {
            throw new GlobalException("未知的文件,获取失败!!!");
        }
        List<String> strings;
        String filePath = RuoYiConfig.getUploadPath() + gwContract.getContractUrl().substring(15);
        try (PDDocument document = PDDocument.load(new File(filePath))) {
            strings = PdfUtil.convertPDFToImages(document);
        } catch (IOException e) {
            e.printStackTrace();
            throw new GlobalException(e.getMessage());
        }
        return AjaxResult.success(strings);
    }

    /**
     * 修改合同管理
     *
     * @param gwContract 合同管理
     * @return 结果
     */
    @Override
    public int updateGwContract(GwContract gwContract) {
        gwContract.setUpdateTime(DateUtils.getNowDate());
        gwContract.setUpdateBy(SecurityUtils.getUsername());
        return gwContractMapper.updateGwContract(gwContract);
    }

    @Override
    public int updateGwContractCallback(GwContract gwContract) {
        gwContract.setUpdateTime(DateUtils.getNowDate());
        return gwContractMapper.updateGwContract(gwContract);
    }

    /**
     * 批量删除合同管理
     *
     * @param ids 需要删除的合同管理主键
     * @return 结果
     */
    @Override
    public int deleteGwContractByIds(String[] ids) {
        return gwContractMapper.deleteGwContractByIds(ids);
    }

    /**
     * 删除合同管理信息
     *
     * @param id 合同管理主键
     * @return 结果
     */
    @Override
    public int deleteGwContractById(String id) {
        //删除明细
        gwContractDetailService.deleteGwContractDetailByMainId(id);
        return gwContractMapper.deleteGwContractById(id);
    }


}
